/**
 * Created by JQ on 2017/1/16.
 */
module.exports = function ($scope, $rootScope, $state, $stateParams, calendarService, $cookies,caseBarDetailjinchengService) {
    // 选择的用户
    $scope.selectedUsers = [];
    // 案件用户列表
    $scope.caseUsers = [];
    // 某个日程的参与者
    $scope.lawerList = [];
    // 新建或者编辑日程弹窗的可选择参与者
    $scope.caseLawyerList = [];
    // 备份案件的参与律师
    $scope.caseLawyerListT = [];

    // 日程全部数据
    $scope.textcad = [];

    // 1：全局日程  3：案件日程
    $scope.searchType = "";
  $scope.qweqwe='09:00';
    $scope.init = function () {
        //上来先隐藏提示框
        $("#textcontent").hide();
        //获取案件类型
      $scope.type = $cookies.get('type');
        //取出当前用户头像路径
        $scope.userPortrait=$cookies.get('userPortraitSave');
        //取出当前用户名字
        $scope.userPortraitName=$cookies.get('userPortraitName');
        //取出当前用户头像
        $scope.userPortraitSave=$cookies.get('userPortraitSave');

        //设置自己的头像
        $scope.settingusertext = portraitsetting($scope.userPortrait,$scope.userPortraitName);

        /*登录ID*/
        $scope.loginId = kbt.decrypt($cookies.get('cookieUserId'));

        /*设置默认添加的日程颜色为红色*/
        $scope.taskcolour = "#D0021B";

        /*保存日程对象*/
        var myCalEvent=new Object();

        $scope.testclick = function () {
            $("#myModal").modal("show");
        };

        $scope.tasknewlist($scope.loginId);

        /*新建日程添加参与人存放数组*/
        $scope.cyList = new Array();
      /*新建案件日程添加参与人存放数组*/
        $scope.caseLawyerIds = new Array();
        jQuery(function ($) {
            /*新建日程-设置颜色*/
          $('#dCalendarColorLump span').click(function(){
            $(this).siblings().find('img').attr('src','');
            $(this).find('img').attr('src','img/checkMark.svg');
          });
          $('#dCalendarColorLump2 span').click(function(){
            $(this).siblings().find('img').attr('src','');
            $(this).find('img').attr('src','img/checkMark.svg');
          });
            $("#task-red").click(function () {
                $scope.taskcolour = "#D0021B";
            });
            $("#task-purple").click(function () {
                $scope.taskcolour = "#F5A623";
            });
            $("#task-blue").click(function () {
                $scope.taskcolour = "#7ED321";
            });
            $("#task-green").click(function () {
                $scope.taskcolour = "#4A90E2";
            });
            /*编辑日程-设置颜色*/
            $("#edit-task-red").click(function () {
                $scope.taskcolour = "#D0021B";
            });
            $("#edit-task-purple").click(function () {
                $scope.taskcolour = "#F5A623";
            });
            $("#edit-task-blue").click(function () {
                $scope.taskcolour = "#7ED321";
            });
            $("#edit-task-green").click(function () {
                $scope.taskcolour = "#4A90E2";
            });

        })

    };


    /**
     * 日期选择器
     */
    // $(".form_datetime").datetimepicker({
    //     format: 'yyyy-mm-dd hh:ii:ss',
    //     language: "zh-CN",
    //     charset: "utf-8",
    //     startView: 2,
    //     weekStart: 1,
    //     //todayBtn:  1,
		// autoclose: "day",
		// todayHighlight: 1,
		// forceParse: "day",
    //     //showMeridian: 1
    // });
  $("#calendar-details-new").datetimepicker({
    minView: "month",
    format: 'yyyy-mm-dd',
    language: "zh-CN",
    charset: "utf-8",
  }).on('changeDate', function (ev) {
    $('#calendar-details-new').datetimepicker('hide');


  });
  /*$("#calendarTime").datetimepicker({
    minView: "hour",
    format: 'hh:ii:ss',
    language: "zh-CN",
    charset: "utf-8",
    startView: 0,
  }).on('changeDate', function (ev) {
    console.log(ev, $(this).val())
    $('#calendarTime').datetimepicker('hide');
  });*/

  $("#calendarDateVal").datetimepicker({
    minView: "month",
    format: 'yyyy-mm-dd',
    language: "zh-CN",
    charset: "utf-8",
  }).on('changeDate', function (ev) {
    $('#calendarDateVal').datetimepicker('hide');


  });

 /* $("#calendarTimeVal").datetimepicker({
    minView: "hour",
    format: 'hh:ii:ss',
    language: "zh-CN",
    charset: "utf-8",
    startView: 0,
  }).on('changeDate', function (ev) {
    $('#calendarTimeVal').datetimepicker('hide');
  });*/



    /**
     * 更改日期事件
     */
    // $('.form_datetime')
    //     .datetimepicker()
    //     .on('changeDate', function () {
    //         //$('.form_datetime').datetimepicker('hide');
    //     });


    /*小时下拉选项数据*/
    $scope.TimeHourXl=[
      {"value":'05:00',"key":'05:00'}, {"value":'05:15',"key":'05:15'}, {"value":'05:30',"key":'05:30'}, {"value":'05:45',"key":'05:45'}, {"value":'06:00',"key":'06:00'}, {"value":'06:15',"key":'06:15'}, {"value":'06:30',"key":'06:30'}, {"value":'06:45',"key":'06:45'}, {"value":'07:00',"key":'07:00'}, {"value":'07:15',"key":'07:15'}, {"value":'07:30',"key":'07:30'}, {"value":'07:45',"key":'07:45'}, {"value":'08:00',"key":'08:00'}, {"value":'08:15',"key":'08:15'}, {"value":'08:30',"key":'08:30'}, {"value":'08:45',"key":'08:45'}, {"value":'09:00',"key":'09:00'}, {"value":'09:15',"key":'09:15'}, {"value":'09:30',"key":'09:30'}, {"value":'09:45',"key":'09:45'},
      {"value":'10:00',"key":'10:00'}, {"value":'10:15',"key":'10:15'}, {"value":'10:30',"key":'10:30'}, {"value":'10:45',"key":'10:45'}, {"value":'11:00',"key":'11:00'}, {"value":'11:15',"key":'11:15'}, {"value":'11:30',"key":'11:30'}, {"value":'11:45',"key":'11:45'}, {"value":'12:00',"key":'12:00'}, {"value":'12:15',"key":'12:15'}, {"value":'12:30',"key":'12:30'}, {"value":'12:45',"key":'12:45'}, {"value":'13:00',"key":'13:00'}, {"value":'13:15',"key":'13:15'}, {"value":'13:30',"key":'13:30'}, {"value":'13:45',"key":'13:45'}, {"value":'14:00',"key":'14:00'}, {"value":'14:15',"key":'14:15'}, {"value":'14:30',"key":'14:30'}, {"value":'14:45',"key":'14:45'},
      {"value":'15:00',"key":'15:00'}, {"value":'15:15',"key":'15:15'}, {"value":'15:30',"key":'15:30'}, {"value":'15:45',"key":'15:45'}, {"value":'16:00',"key":'16:00'}, {"value":'16:15',"key":'16:15'}, {"value":'16:30',"key":'16:30'}, {"value":'16:45',"key":'16:45'}, {"value":'17:00',"key":'17:00'}, {"value":'17:15',"key":'17:15'}, {"value":'17:30',"key":'17:30'}, {"value":'17:45',"key":'17:45'}, {"value":'18:00',"key":'18:00'}, {"value":'18:15',"key":'18:15'}, {"value":'18:30',"key":'18:30'}, {"value":'18:45',"key":'18:45'}, {"value":'19:00',"key":'19:00'}, {"value":'19:15',"key":'19:15'}, {"value":'19:30',"key":'19:30'}, {"value":'19:45',"key":'19:45'},
      {"value":'20:00',"key":'20:00'}, {"value":'20:15',"key":'20:15'}, {"value":'20:30',"key":'20:30'}, {"value":'20:45',"key":'20:45'}, {"value":'21:00',"key":'21:00'}, {"value":'21:15',"key":'21:15'}, {"value":'21:30',"key":'21:30'}, {"value":'21:45',"key":'21:45'}, {"value":'22:00',"key":'22:00'}, {"value":'22:15',"key":'22:15'}, {"value":'22:30',"key":'22:30'}, {"value":'22:45',"key":'22:45'}, {"value":'23:00',"key":'23:00'}, {"value":'23:15',"key":'23:15'}, {"value":'23:30',"key":'23:30'}, {"value":'23:45',"key":'23:45'}, {"value":'00:00',"key":'00:00'}, {"value":'00:15',"key":'00:15'}, {"value":'00:30',"key":'00:30'}, {"value":'00:45',"key":'00:45'}
    ];

    /**
     * 日程列表
     * @param id
     */
    $scope.tasknewlist = function (id) {
        if($state.current.url == '/schedule') {
            $scope.searchType = 1;
            calendarService.gaintaklist(id).then(function (data) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
                if (data.code == 1) {
                  //日程初始 原始数据
                    setlist(data.data);
                }
            }, function (response) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
                console.error('gaintaklist error', response.status, response.statusText);
            });
        }
        else if($state.current.url == '/calendar') {

            $scope.searchType = 3;
            $rootScope.loadingShow = true;
            $rootScope.fadeShow = true;
            $scope.selectedUsers = [];
          if($scope.searchType==3&&$rootScope.typeIf==7){
            $scope.ifType=false;
          }else{
            $scope.ifType=true;
          }

            calendarService.casetasklist(id, $scope.selectedUsers, $cookies.get('caseAppId')).then(function (data) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
                if (data.code == 1) {
                  setlist(data.data);
                  $('.fc-day').bind('click',function(){
                    $('#calendar-new').modal('hide');
                  })
                  // $scope.caseLawyerList = data.datamember;
                  if ($scope.caseUsers.length < 1) {
                      $scope.caseUsers = data.datamember;
                      angular.copy(data.datamember,$scope.caseLawyerList);
                      angular.copy(data.datamember,$scope.caseLawyerListT);
                  }


                }
            }, function (response) {
              $rootScope.loadingShow = false;
              $rootScope.fadeShow = false;
              console.error('gaintaklist error', response.status, response.statusText);
            });
        }
    };


    /**
     * 选择用户刷新日程列表
     * @param id
     */
    $scope.refleshtasklist = function (id) {

        $rootScope.loadingShow = true;
        $rootScope.fadeShow = true;
        $scope.selectedUsers = [];
        angular.forEach($scope.caseUsers, function (user) {
          if (user.isselect) {
            $scope.selectedUsers.push(user.id);
          }
        })
        calendarService.casetasklist(id, $scope.selectedUsers, $cookies.get('caseAppId')).then(function (data) {
          $rootScope.loadingShow = false;
          $rootScope.fadeShow = false;
          if (data.code == 1) {
            if ($scope.caseUsers.length < 1) {
              $scope.caseUsers = data.datamember;

            }
            var tasklistarray = [];
            if (data.data.length > 0)
              for (var i = 0; i < data.data.length; i++) {
                var task = new Object();
                task.title = data.data[i].schedule;
                task.start = data.data[i].beginTime;
                task.end = data.data[i].endTime;
                task.color = data.data[i].colour;
                task.id = data.data[i].id;
                task.description = data.data[i].description;
                task.editable = false;
                task.remindTime = data.data[i].remindPoint;
                tasklistarray.push(task);
              }

            $('#calendar').fullCalendar( 'removeEventSource',$scope.textcad);
            $scope.textcad = tasklistarray;
            $('#calendar').fullCalendar( 'addEventSource', $scope.textcad);
          }
        }, function (response) {
          $rootScope.loadingShow = false;
          $rootScope.fadeShow = false;
          console.error('gaintaklist error', response.status, response.statusText);
        });
      // }
    };

  /*提醒下拉*/
  $scope.remindList = [
    {id:0, name:'关闭提醒'},
    {id:1, name:'开始时提醒'},
    {id:2, name:'5分钟前'},
    {id:3, name:'15分钟前'},
    {id:4, name:'30分钟前'},
    {id:5, name:'1小时前'},
    {id:6, name:'2小时前'},
    {id:7, name:'1天前'}
  ];

    /**
     * 新增日程任务
     * @param result1 日程标题
     * @param taskcolour 日程颜色
     * @param timenow 开始时间
     * @param timefinish 结束时间
     * @param calendar 日历对象
     * @param userIds 参与人ID
     * @param remindTime 提醒时间
     */
    $scope.uploadingtask = function (result1, taskcolour, timenow, timefinish, calendar, userIds,remindTime,result2) {
        $rootScope.loadingShow = true;
        $rootScope.fadeShow = true;
        var caseId = "";
        if ($scope.searchType == 3)
          caseId = $cookies.get('caseAppId');
        $cookies.get('caseAppId');


        calendarService.establishtask(result1, taskcolour, timenow, timefinish, $scope.loginId, userIds, $scope.userPortraitName,$scope.searchType,
          caseId, "", "",remindTime,result2
        ).then(function (data) {
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
            if (data.code == 1) {
                var taskTemple = {
                    title: result1,
                    start: timenow,
                    end: timefinish,
                    color: taskcolour,
                    editable: false,
                    id:data.workScheduleId,
                  remindTime:remindTime,
                  description:result2
                }
                // //本地添加日程
                // calendar.fullCalendar('renderEvent', taskTemple, true // make the event "stick"
                // );
                //重新加载列表
                // $scope.tasknewlist($scope.loginId);
                //parent.document.location.reload();
                //  calendar.fullCalendar('renderEvent')

                $('#calendar').fullCalendar( 'removeEventSource',$scope.textcad);
                $scope.textcad.push(taskTemple);
                $('#calendar').fullCalendar( 'addEventSource', $scope.textcad);
                $scope.cyList.splice(0,$scope.cyList.length);
                $("#calendar-new").modal("hide");
            }
        }, function (response) {

            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
            console.error('updatemessage error', response.status, response.statusText);
        });

    };


    /**
     * 增加时间
     * @param date
     * @param minutes
     * @returns {Date}
     */
    function addMinutes(date, minutes) {
        minutes = parseInt(minutes);
        var interTimes = minutes * 60 * 1000;
        interTimes = parseInt(interTimes);
        return new Date(Date.parse(date.replace(/\-/g, "/")) + interTimes);
    }

    /**
     * 设置日历
     * @param data
     */
    function setlist(data) {
        var tasklistarray = [];
        if (data.length > 0)
          for (var i = 0; i < data.length; i++) {
              var task = new Object();
              task.title = data[i].schedule;
              task.start = data[i].beginTime;
              task.end = data[i].endTime;
              task.color = data[i].colour;
              task.id = data[i].id;
              task.description = data[i].description;
              task.editable = false;
              task.remindTime = data[i].remindPoint;
              tasklistarray.push(task);
          }

        $scope.textcad =tasklistarray;

        jQuery(function ($) {
          if($scope.searchType != 3){
            $('#d-close-cal').css({'top':'-800px','display':'block'}).stop().animate({top:'12px'},805);
            $('#calendar').css({'position':'relative','top':'-800px'}).stop().animate({top:0},805);

            $('#d-close-cal').click(function(){
              $('#calendar').stop().animate({top:'-1400px'},900);
              $(this).css('display','none');
              setTimeout(function(){
                $state.go('workBarNoWork')
              },700);
            })
          }

          // $('.LawyerAddBody3').hide();
            $('#external-events div.external-event').each(function () {
                // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
                // it doesn't need to have a start or end 它不需要有一个开始或结束
                var eventObject = {
                    title: $.trim($(this).text()) // use the element's text as the event title 使用元素的文本事件标题
                };
                // store the Event Object in the DOM element so we can get to it later 将事件对象存储在DOM元素我们可以得到它
                $(this).data('eventObject', eventObject);

                // make the event draggable using jQuery UI 可拖动的使用jQuery UI事件
                $(this).draggable({
                    zIndex: 999,
                    revert: true,      // will cause the event to go back to its 将导致事件回到它的?
                    revertDuration: 0  //  original position after the drag 原始位置后的阻力?
                });

            });

            var calendar = $('#calendar').fullCalendar({
                //isRTL: true,
                //firstDay: 1,// >> change first day of week
                buttonHtml: {
                    prev: '<i class="ace-icon fa fa-chevron-left"></i>',
                    next: '<i class="ace-icon fa fa-chevron-right"></i>'
                  // , today: '<i class="ace-icon fa fa-chevron-right"></i>'
                },
             /* buttonHtml: {
                prev: '<img src="img/lastMonth.svg"/>',
                next: '<img src="img/nextMonth.svg"/>'
              },*/
              header: {
                    left: 'prev,next,today',
                    center: 'title',
                    right: 'month,agendaDay' // agendaWeek,
                  /*agendaDay 日*/
                },
                monthNames: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
              	monthNamesShort: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
              	dayNames: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
              	dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
              	today: ["今天"],
	              firstDay: 1,
	              buttonText: {
	                  today: '当前月日',
	                  month: '月',
                    // week: '周',
	                  day: '日',
	                 /* prev: '<',
	                  next: '>'*/
	              },
                events: $scope.textcad,
                views: {
                  month: {
                    titleFormat: 'YYYY年 MMMM'
                  },
                  agendaDay: {
                    titleFormat: 'YYYY年 MMMM DD'
                  }
                },
                timezone:'local',
                timeFormat: 'HH:mm',
                theme:false,
                slotLabelFormat:"HH:mm",
                slotDuration:'00:15:00',// 日视图插槽间隔
                allDaySlot:false,//是否显示全天
                editable: true,
                droppable: true, // this allows things to be dropped onto the calendar !!!
                drop: function (date) { // this function is called when something is dropped

                    // retrieve the dropped element's stored Event Object
                    var originalEventObject = $(this).data('eventObject');
                    var $extraEventClass = $(this).attr('data-class');


                    // we need to copy it, so that multiple events don't have a reference to the same object
                    var copiedEventObject = $.extend({}, originalEventObject);

                    // assign it the date that was reported
                    copiedEventObject.start = date;
                    copiedEventObject.allDay = false;
                    if ($extraEventClass) copiedEventObject['className'] = [$extraEventClass];

                    // render the event on the calendar
                    // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
                    $('#calendar').fullCalendar('renderEvent', copiedEventObject, true);

                    // is the "remove after drop" checkbox checked?
                    if ($('#drop-remove').is(':checked')) {
                        // if so, remove the element from the "Draggable Events" list
                        $(this).remove();
                    }
                    $('#calendar .fc-header-toolbar').appendChild('<img src="../img/d_close.svg"/>')
                }
                ,
                selectable: true,
                selectHelper: true,


                /**
                 * 新建日程
                 * @param date
                 * @param calEvent
                 * @param start
                 * @param end
                 * @param allDay
                 */
                select: function (date, calEvent, start, end, allDay) {
                  $("#input_text1").focus();
                    var hour = null;
                    var min = null;
                  // console.log(date._i instanceof Array,date._i.constructor===Array)
                    if (date._i instanceof Array) {
                      hour =date._i[3].toString().length<= 1 ?('0'+date._i[3]):date._i[3];
                      min =date._i[4].toString().length<= 1 ?(date._i[4]+'0'):date._i[4];
                    }
                  var date = new Date(date);
                    if ( hour != null) {
                        /*date.setHours(hour);
                        date.setMinutes(min);*/
                      $scope.timeHm=hour+':'+min;
                      $scope.$apply();
                      // $scope.AssignmentQwe($scope.qweqwe)
                    }

                    if($rootScope.typeIf!=7){
                      $("#calendar-new").modal("show");
                    }


                    $('#textcontent').css('display','none');
                    $('.LawyerAddBody3').hide();
                  $('#dCalendarColorLump span').find('img').attr('src','');
                  $("#input_text2").val('');

                    $("#input_text1").val("");
                    $('#calendar-details-new').val(date.pattern("yyyy-MM-dd"));
                    // $('#calendar-details-new').val("");
                    // $('#calendarTime').val(date.pattern("HH:mm:ss"));

                    // $('#remindTime').val($scope.remindList[1].name);
                    //  $scope.remindTime = $scope.remindList[1].name;
                    $('#my-count').text(0);
                    $scope.taskcolour = "red";

                     // $("#calendar-details-new").val(date.pattern("yyyy-MM-dd"));
                     // $('#calendarTime').val(date.pattern("HH:mm:ss"));

                    // $("#calendar-details-new-time").val(date.pattern("HH:mm:ss"));
                  // $("#calendar-details-new").val(date.pattern("yyyy-MM-dd"));
                  // $("#calendar-details-new-time").val(date.pattern("HH:mm:ss"));

                    $("#button_text1").unbind('click').click(function () {

                        var result1 = $("#input_text1").val();
                        var result2 = $("#input_text2").val();
                        if(result1==""){
                          $('#textcontent').css('display','block');
                        }
                        var calendarDate = $('#calendar-details-new').val();

                        var calendarTime =$('#calendarTime').val()!=''?$('#calendarTime').val().slice($('#calendarTime').val().indexOf(':')+1,$('#calendarTime').val().length)+':00':'05:00:00';

                        var timenow = calendarDate + " " + calendarTime;
                        var timefinish = addMinutes(timenow, 15).pattern("yyyy-MM-dd HH:mm:ss");
                        var remindTime = $scope.remindTime;
                        //   var timenow = $("#calendar-details-new").val() + $("#calendar-details-new-time").val();
                        //   var timefinish = addMinutes(timenow, 15).pattern("yyyy-MM-dd");

                        // 标题
                        // console.log(result1);
                        // //颜色值
                        // console.log($scope.taskcolour);
                        // //时间
                        //
                        if (result1 !== "") {
                            /*参与人ID*/
                            var userIds = "";
                            for (var i=0;i<$scope.cyList.length;i++){
                                if(i!=$scope.cyList.length-1){
                                    userIds +=$scope.cyList[i].id+"!%!";
                                }else{
                                    userIds +=$scope.cyList[i].id;
                                }
                            }

                            //请求网络上传日程
                            $scope.uploadingtask(result1, $scope.taskcolour, timenow, timefinish, calendar, userIds,remindTime,result2);

                        } else {
                            //如果没有标题就提示一下
                            $("#textcontent").show();
                        }
                    });
                    //提示消息取消的按钮
                    $("#textcontent2").unbind('click').click(function () {
                        $("#textcontent").hide();
                    });

                    angular.copy($scope.caseLawyerListT, $scope.caseLawyerList);
                }
                ,
                /**
                 * 编辑日程
                 * @param calEvent
                 */
                eventClick: function (calEvent) {

                  var date = new Date(calEvent.start._i);
                  var calEventStartD = calEvent.start._i;
                    myCalEvent = calEvent;

                  $('.LawyerAddBody3').hide();//打开时隐藏此项

                    /*获取当前处于哪个视图*/
                    var view = $('#calendar').fullCalendar('getView');

                    /*如果当前视图是日视图,则隐藏查看详情按钮;如果当前视图是月视图,则显示查看详情按钮*/
                    if (view.name == 'agendaDay') {
                        $('#calendarDetailEdit').hide();
                    } else if (view.name == 'month') {
                        $('#calendarDetailEdit').show();
                    }

                    /*设置任务标题*/
                    $('#calendar-task-title').val(calEvent.title);
                    $('#my-count-edit').text(calEvent.title.length);
                    $('#calendar-task-title2').val(calEvent.description);

                     $('#calendarDateVal').val(date.pattern("yyyy-MM-dd"));
                     // $('#calendarTimeVal').val(date.pattern("HH:mm:ss"));
                   $scope.calendarDateTimeModal=calEventStartD.slice(calEventStartD.indexOf(' ')+1,calEventStartD.lastIndexOf(':'));

                     $scope.remindTime = calEvent.remindTime;

                  //颜色默认选中
                  if(calEvent.color == "#D0021B"){
                    $("#edit-task-red").siblings().find('img').attr('src','');
                    $("#edit-task-red").find('img').attr('src','img/checkMark.svg');
                  }else if(calEvent.color =="#F5A623"){
                    $("#edit-task-purple").siblings().find('img').attr('src','');
                    $("#edit-task-purple").find('img').attr('src','img/checkMark.svg');
                  }else if( calEvent.color == "#7ED321"){
                    $("#edit-task-blue").siblings().find('img').attr('src','');
                    $("#edit-task-blue").find('img').attr('src','img/checkMark.svg');
                  }else if(calEvent.color == "#4A90E2"){
                    $("#edit-task-green").siblings().find('img').attr('src','');
                    $("#edit-task-green").find('img').attr('src','img/checkMark.svg');
                  }else{
                    $("#edit-task-red").siblings().find('img').attr('src','');
                    $("#edit-task-red").find('img').attr('src','img/checkMark.svg');
                  }
                  /*设置任务时间*/
                    // $('#calendar-details-timeval').val(calEvent.start._i);
                    /*显示弹出框*/
                    if($rootScope.typeIf!=7){
                      $('#calendar-details').modal('show');
                    }



                    /*查询日程参与人*/
                    $scope.queryWorksCheduleParticipant(calendar, calEvent);

                    /*更新操作*/
                    $scope.updateTask = function () {

                      bootbox.dialog({
                        message: "你确定要更新日程?",
                        title: "更新日程",
                        className:'d-promptBox',
                        buttons: {
                          OK: {
                            label: "确定",
                            className: "d-btn-confirm",
                            callback: function () {

                              $scope.updateCalendar(calendar, calEvent);
                            }
                          },
                          Cancel: {
                            label: "取消",
                            className: "d-btn-cancel",
                            callback: function () {

                            }
                          }
                        }
                      });

                    };

                    /*删除操作*/
                    $scope.deleteTask = function () {
                      bootbox.dialog({
                        message: "你确定删除日程?",
                        title: "删除日程",
                        className:'d-promptBox',
                        buttons: {
                          OK: {
                            label: "确定",
                            className: "d-btn-confirm",
                            callback: function () {
                              $scope.deleteCalendar(calendar, calEvent);
                            }
                          },
                          Cancel: {
                            label: "取消",
                            className: "d-btn-cancel",
                            callback: function () {

                            }
                          }
                        }
                      });

                    };

                    // /*重新加载操作*/
                    // $scope.reloadTask = function () {
                    //   $scope.reloadCalendar(calendar, calEvent);
                    // };

                    /*查看详情*/
                    $scope.turnDetails = function () {
                        //跳转日视图
                        calendar.fullCalendar('changeView', 'agendaDay');
                        //跳转点击哪天的视图
                        calendar.fullCalendar('gotoDate', new Date(calEvent.start._i.replace(/\-/g, "/")));
                        //隐藏弹出框
                        $('#calendar-details').modal('hide');
                    };

                    angular.copy($scope.caseLawyerListT, $scope.caseLawyerList);
                }

            });

        });

        // /**
        //  * 重新加载日程任务
        //  */
        // $scope.reloadCalendar = function (calendar, calEvent) {
        //     calendar.fullCalendar('refetchEvents');
        // };

        /**
         * 编辑日程-删除日程任务
         */
        $scope.deleteCalendar = function (calendar, calEvent) {
            $rootScope.loadingShow = true;
            $rootScope.fadeShow = true;
          var caseId = $cookies.get('caseAppId');
            calendarService.deleteCalendar(caseId, calEvent.id,$scope.userPortraitName,$scope.loginId).then(function (data) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
                if (data.code == 1) {
                    calendar.fullCalendar('removeEvents', function (ev) {
                        return (ev._id == calEvent._id);
                    });
                    //隐藏弹出框
                    $('#calendar-details').modal('hide');
                }
            }, function (response) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
                console.error('deleteCalendar error', response.status, response.statusText);
            });

        };

        /**
         * 编辑日程-更新日程任务
         */
        $scope.updateCalendar = function (calendar, calEvent) {
            $rootScope.loadingShow = true;
            $rootScope.fadeShow = true;
            calEvent.title = $('#calendar-task-title').val();
            calEvent.color = $scope.taskcolour;
          calEvent.description =$('#calendar-task-title2').val();

           // 原始的时间设置
           // calEvent.start = $('#calendar-details-timeval').val();
           // calEvent.end = addMinutes(calEvent.start, 15).pattern("yyyy-MM-dd HH:mm:ss");
            //目前修改的时间
            var cDate = $('#calendarDateVal').val();
            var cTime = $('#calendarTimeVal').val().slice($('#calendarTimeVal').val().indexOf(':')+1,$('#calendarTimeVal').val().length)+':00';

            calEvent.start = cDate + " " + cTime;
            calEvent.end = addMinutes(calEvent.start, 15).pattern("yyyy-MM-dd HH:mm:ss");
            // var remindTime = calEvent.remindTime;
            var remindTime = $scope.remindTime;

            var caseId = $cookies.get('caseAppId');
            calendarService.updateCalendar(caseId,calEvent.id, calEvent.title, calEvent.start,calEvent.end, calEvent.color, $scope.loginId,remindTime,calEvent.description).then(function (data) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
                if (data.code == 1) {
                    // calendar.fullCalendar('updateEvent', calEvent);
                  for (var i=0;i<$scope.textcad.length;i++){
                    if($scope.textcad[i].id == calEvent.id) {
                      $scope.textcad[i].title = calEvent.title;
                      $scope.textcad[i].start = calEvent.start;
                      $scope.textcad[i].end = calEvent.end;
                      $scope.textcad[i].color = calEvent.color;
                      $scope.textcad[i].description= calEvent.description;
                      $scope.textcad[i].remindTime = remindTime;
                    }
                  }
                  calendar.fullCalendar( 'removeEventSource', $scope.textcad);
                  calendar.fullCalendar( 'addEventSource', $scope.textcad);
                  calendar.fullCalendar( 'refetchEvents' );

                    //重新获取日程
                    // $scope.tasknewlist($scope.loginId);

                    //隐藏弹出框
                    $('#calendar-details').modal('hide');
                }
            }, function (response) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
                console.error('updateCalendar error', response.status, response.statusText);
            });

        };
$scope.AssignmentQwe=function(strI){
  $scope.timeHm=strI;
}
        /**
         * 编辑日程-查询日程参与人
         */
        $scope.queryWorksCheduleParticipant = function (calendar, calEvent) {
            $rootScope.loadingShow = true;
            $rootScope.fadeShow = true;
            calendarService.queryWorksCheduleParticipant(calEvent.id).then(function (data) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
                if (data.code == 1) {
                    $scope.lawerList = data.data;
                    // 将已有的参与者删除掉
                    var deleteIndexs = new Array();
                    for(var bb = 0; bb < $scope.caseLawyerList.length; bb++) {
                      for(var cc = 0; cc < $scope.lawerList.length; cc++) {
                        if ($scope.lawerList[cc].id == $scope.caseLawyerList[bb].id) {
                          deleteIndexs.push(bb);
                        }
                      };
                    };
                    // 从后往前删除
                    for (var deleteindex = deleteIndexs.length - 1; deleteindex >= 0; deleteindex--) {
                      $scope.caseLawyerList.splice(deleteIndexs[deleteindex], 1);
                    };
                }
            }, function (response) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
                console.error('queryWorksCheduleParticipant error', response.status, response.statusText);
            });

        };

    }

    /**
     * 编辑日程-判断键盘事件
     */
    $scope.addXieZhuInputEnter = function () {
      if($('#addXieZhuInput').val()!=''&&$('#addXieZhuInput').val().length>1){
        var myIndex=$('#addXieZhuInput').val();
        if ($scope.cellphone != '') {
          $rootScope.loadingShow = true;
          $rootScope.fadeShow = true;
          $scope.CaseLawyerTianSelect =[];
          var caseId = "";
          if ( $scope.searchType == 3)
            caseId = $cookies.get('caseAppId');
          calendarService.CaseLawyerTian($scope.cellphone, $scope.searchType, caseId, myCalEvent.id).then(function (data) {
            $('.LawyerboxUl').show();
            // $('.LawyerboxUl').css("height", "100px");
            $('.LawyerAddBody3').css("min-height", "230px");
            $scope.Search=myIndex;
            if (data.code == 1) {
              $scope.CaseLawyerTianSelect = data;
              $scope.CaseLawyerTianButton = function (name, LawyerId,index) {
                calendarService.updateWorksCheduleParticipant(myCalEvent.id, LawyerId, 3, $scope.userPortraitName, $scope.loginId).then(function (data) {
                  $rootScope.loadingShow = false;
                  $rootScope.fadeShow = false;
                  if (data.code == 1) {
                    bootbox.alert({
                      size: "small",
                      title: "提示信息",
                      message: "添加成功，耐心等待参与人确认",
                      callback: function(){ /* your callback code */ }
                    });

                    var dTjUser = {
                      username:$scope.CaseLawyerTianSelect.data[index].username,
                      id:$scope.CaseLawyerTianSelect.data[index].id,
                      iconUrl:$scope.CaseLawyerTianSelect.data[index].iconUrl
                    };
                    $(".LawyerAddBody3").addClass('hide');
                    $scope.lawerList.push(dTjUser);

                    $scope.cellphone = "";
                  }
                }, function (response) {
                  $rootScope.loadingShow = false;
                  $rootScope.fadeShow = false;
                  console.error('updateWorksCheduleParticipant error', response.status, response.statusText);
                });

              };
              //点击关闭
              $scope.CaseLawyerClose = function () {
                $scope.CaseLawyerTianModel = "";
              };
              $(".LawyerboxUlbutton").show()
              $('#error-text').hide();
            } else {
              $('#error-text').show();
              $(".LawyerboxUlbutton").hide()
            }
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
          }, function () {
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
          });


        }
      }

    };

    /**
     * 添加日程-判断键盘事件
     */
    $scope.addCanyuInputEnter = function ($event) {

      if($('#addCanyuInput').val()!=''&&$('#addCanyuInput').val().length>1){
        var myIndex=$('#addCanyuInput').val();
        if ($scope.cellphone != '') {
          $rootScope.loadingShow = true;
          $rootScope.fadeShow = true;
          var caseId = "";
          if ( $scope.searchType == 3)
            caseId = $cookies.get('caseAppId');
          calendarService.CaseLawyerTian($scope.cellphone, $scope.searchType, caseId).then(function (data) {
            if ($scope.cellphone != '') {
              $('.LawyerboxUl').show();
              // $('.LawyerboxUl').css("height", "100px");
              $('.LawyerAddBody3').css("min-height", "230px");
              $scope.CaseLawyerTianSelect = [];
              if (data.code == 1) {
                $scope.CaseLawyerTianSelect = data;
                 $scope.Search=myIndex;
                //点击关闭
                $scope.CaseLawyerClose = function () {
                  $scope.CaseLawyerTianModel = "";
                };
                $(".LawyerboxUlbutton").show();
                $('#error-add-text').hide();
              } else {
                $(".LawyerboxUlS").html("未搜索到结果");
                $(".LawyerboxUlbutton").hide();
                $('#error-add-text').show();
              }
              $rootScope.loadingShow = false;
              $rootScope.fadeShow = false;
            }
          }, function () {
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
          });
        }
      }else{
        $('.LawyerboxUl').hide();
      }

    };

    /**
     * 编辑日程-删除日程参与人
     * @param LawyerId 参与人ID
     * @constructor
     */
    $scope.CaseLawyerDel = function (LawyerId) {

        calendarService.updateWorksCheduleParticipant(myCalEvent.id, LawyerId,9,$scope.userPortraitName,$scope.loginId).then(function (data) {
            // $rootScope.loadingShow = true;
            // $rootScope.fadeShow = true;
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
            if (data.code == 1) {

                $scope.queryWorksCheduleParticipant(calendar,myCalEvent);
            }
        }, function (response) {
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
            console.error('updateWorksCheduleParticipant error', response.status, response.statusText);
        });
    };




    /**
     * 新建日程-添加参与人
     * @param name
     * @param LawyerId
     * @constructor
     */
    $scope.CanYuTianButton = function (index,caseUser) {
        /*避免重复添加*/
        for (var i=0;i<$scope.cyList.length;i++){
            if($scope.cyList[i].userId == caseUser.id){
                bootbox.alert({
                    size: "small",
                    title: "提示信息",
                    message: "不能重复添加参与人",
                    callback: function(){ /* your callback code */ }
                });
                return;
            }
        }
      var cyUser = {
        username:caseUser.username,
        userId:caseUser.id,
        userIcon:caseUser.iconUrl
      };
        $scope.cyList.push(cyUser);
         $('.LawyerAddBody3').addClass('hide');
      $scope.caseUsers.splice(index,1);

        $scope.cellphone = "";
    };

  /**
   * 案件日程-添加参与人
   * @param name
   * @param LawyerId
   * @constructor
   */

  $scope.addLawyerMem = function (index,caseUser,type) {
    /*避免重复添加*/
    for (var i=0;i<$scope.cyList.length;i++){
      if($scope.cyList[i].userId == caseUser.id){
        bootbox.alert({
          size: "small",
          title: "提示信息",
          message: "不能重复添加参与人",
          callback: function(){ /* your callback code */ }
        });
        return;
      }
    }
    var cyUser = {
      username:caseUser.username,
      userId:caseUser.id,
      userIcon:caseUser.iconUrl
    };
    if (type == 1) {
      $scope.cyList.push(caseUser);
      $scope.caseLawyerList.splice(index,1);
    } else {
      // 更新日程时，需要实时请求增加
      if(type == 2) {
        calendarService.updateWorksCheduleParticipant(myCalEvent.id, caseUser.id, 1, $scope.userPortraitName, $scope.loginId).then(function (data) {
          $rootScope.loadingShow = false;
          $rootScope.fadeShow = false;
          if (data.code == 1) {
            $scope.lawerList.push(caseUser);
            $scope.caseLawyerList.splice(index,1);
            // $scope.queryWorksCheduleParticipant(calendar,myCalEvent);
          }
        }, function (response) {
          $rootScope.loadingShow = false;
          $rootScope.fadeShow = false;
          console.error('updateWorksCheduleParticipant error', response.status, response.statusText);
        });
      }
    }
    $('.LawyerAddBody3').addClass('hide');
    $scope.cellphone = "";
  };

  /**
   * 案件日程-删除参与人
   * @param name
   * @param LawyerId
   * @constructor
   */
  $scope.delLawyerMem = function (Lawyer,index,type) {

    if(type==1){
      $scope.cyList.splice(index,1);
      $scope.caseLawyerList.push(Lawyer);
    }else{
      // 更新日程时，需要实时请求删除
      if(type == 2) {
        calendarService.updateWorksCheduleParticipant(myCalEvent.id, Lawyer.id, 9, $scope.userPortraitName, $scope.loginId).then(function (data) {
          $rootScope.loadingShow = false;
          $rootScope.fadeShow = false;
          if (data.code == 1) {
            $scope.lawerList.splice(index,1);

            var flag = false;
            for(var indext = 0; indext < $scope.caseLawyerList.length; indext++) {
              if(Lawyer.id == $scope.caseLawyerList[indext].id) {
                flag = true;
              }
            }
            if (!flag) {
              $scope.caseLawyerList.push(Lawyer);
            }
            // $scope.queryWorksCheduleParticipant(calendar,myCalEvent);
          }
        }, function (response) {
          $rootScope.loadingShow = false;
          $rootScope.fadeShow = false;
          console.error('updateWorksCheduleParticipant error', response.status, response.statusText);
        });
      }
    }

    // for (var i=0;i<$scope.cyList.length;i++){
    //   if($scope.cyList[i].userId == LawyerId){
    //     $scope.cyList.splice(i,1);
    //     $scope.caseLawyerIds.splice(i,1);
    //     return;
    //   }
    // }
  };

    /**
     * 新建日程-删除参与人
     * @param name
     * @param LawyerId
     * @constructor
     */
    $scope.delCanyu = function (LawyerId) {
        for (var i=0;i<$scope.cyList.length;i++){
            if($scope.cyList[i].userId == LawyerId){
                 $scope.cyList.splice(i,1);
                return;
            }
        }
    };

    $scope.titleLen = 0;
    $('#input_text1').bind('input propertychange', function() {
        $scope.titleLen = $('#input_text1').val().length;
        $('#my-count').text($scope.titleLen);
    });

    $scope.titleLenEdit = 0;
    $('#calendar-task-title').bind('input propertychange', function() {
        $scope.titleLenEdit = $('#calendar-task-title').val().length;
        $('#my-count-edit').text($scope.titleLenEdit);
    });

    $(".join-per-p").bind("click", function () {
        $scope.CaseLawyerTianSelect = [];
        $scope.$apply();
        $("#addXieZhuInput").val("");
        $(".LawyerAddBody3").show();
        $scope.cellphone = "";
      $('.LawyerboxUl').hide();
    });


    $(".LawyerAddBody3 .Add-close").on("click", function () {
        $scope.CaseLawyerTianSelect = [];
        $scope.$apply();
        $("#addXieZhuInput").val("");
        $(".LawyerAddBody3").addClass("hide");
        $scope.cellphone = "";
    });


    $scope.init();

};
